package com.sinoglobal.dumping.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_LogIn_BaseVo;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lsh
 * @createdate 2015-6-1 下午2:45:01
 * @Description: TODO(用一句话描述该类做什么)无密码快速登录类
 */

public class Dumpling_NoPasswordQuicklyLoginActivity extends Dumpling_SinoBaseActivity implements OnClickListener {
	private EditText registerPhone; // 用户名
	private EditText registerPassword;// 验证码
	private Button reight_identifyingcode_btn;// 验证码按钮
	private TextView verification_code_error; // 验证码错误
	private Button registerBtn;// 设置密码按钮
	private TextView knowRules;// 了解信诺通信证
	private String identifyingCodeStr;// 验证码
	private String phone; // 用户名
	private int recLen = 60;
	private String proIden = Dumpling_SinoConstans.PRODUCT_CODE;
	private boolean phoneflag = false;
	// private VerifyUtil verifyUtil;
	private boolean verificationflag = false;
	private String phoneId = "";
	private boolean agreeflag = false;
	private int mIndedx =-1;
   
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        View view = getView(R.id.title_right_btn_share);
        hideView(mTemplateRightText, mTemplateRightImg,view);
        mTemplateTitleText.setText("快速登录");

        setContentView(R.layout.dumpling_activity_find_password);
		
		mIndedx = getIntent().getIntExtra("index",-1);
		
		init();
		addListener();
        
		try {
			TelephonyManager tm = (TelephonyManager) Dumpling_NoPasswordQuicklyLoginActivity.this
					.getSystemService(Context.TELEPHONY_SERVICE);
			phoneId = tm.getLine1Number();
			if (!phoneId.equals("") && phoneId != null) {
				String subPhone = phoneId.substring(phoneId.length() - 11,
						phoneId.length());
				registerPhone.setText(subPhone);
				agreeflag = true;
			}
		} catch (Exception e) {
			
		}
	}
    
	public void init() {
		registerBtn = (Button) this.findViewById(R.id.reight_btn);
		registerBtn.setClickable(false);
		registerBtn.setText("登录");
		registerPhone = (EditText) this.findViewById(R.id.reight_phone);
		registerPassword = (EditText) this
				.findViewById(R.id.reight_identifyingcode_et);
		reight_identifyingcode_btn = (Button) this
				.findViewById(R.id.reight_identifyingcode_btn);
		verification_code_error = (TextView) this
				.findViewById(R.id.forget_pwd_tv);
		knowRules = (TextView) this.findViewById(R.id.quickly_login_rules);
	}


	public void addListener() {
		registerBtn.setOnClickListener(this);
		reight_identifyingcode_btn.setOnClickListener(this);
		knowRules.setOnClickListener(this);
		registerPhone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				phone = registerPhone.getText().toString();
				String validPhoto = validPhone(phone);
				if (!TextUtils.isEmpty(validPhoto)) {
					phoneflag = false;
					registerBtn.setClickable(false);
					registerBtn
							.setBackgroundResource(R.drawable.dumpling_nottouch_button);
				} else {
					phoneflag = true;
					if (verificationflag) {
						registerBtn.setClickable(true);
						registerBtn
								.setBackgroundResource(R.drawable.dumpling_apply_btn_selector_moring);
					}
				}

			}
		});
		registerPassword.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				identifyingCodeStr = registerPassword.getText().toString();
				String validIdentifyingCode = validIdentifyingCode(identifyingCodeStr);
				if (!TextUtils.isEmpty(validIdentifyingCode)) {
					verificationflag = false;
					registerBtn.setClickable(false);
					registerBtn
							.setBackgroundResource(R.drawable.dumpling_nottouch_button);
				} else {
					verificationflag = true;
					if (phoneflag) {
						registerBtn.setClickable(true);
						registerBtn
								.setBackgroundResource(R.drawable.dumpling_apply_btn_selector_moring);
					}
				}
			}
		});
	}

	public String validPhone(String phone) {
		String message = "";
		if (TextUtils.isEmpty(phone.replace(" ", ""))) {
			message = "请输入手机号码！";
		} else if (phone.length() < 11) {
			message = "请输入11位手机号码！";
		} else {
			/*
			 * if("14527060199".equals(phone)){ //测试所用 return message; }
			 */
			// String phoneRule = "^[1]+[3,5,8]+[0-9]{9}";
			// String phoneRule =
			// "^((14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
			String phoneRule = "^(1[3-9][0-9])\\d{8}$";
			Pattern p = Pattern.compile(phoneRule);
			Matcher match = p.matcher(phone);
			if (!match.matches()) {
				message = "请输入正确的手机号码！";
			}
		}
		return message;
	}

	public String validIdentifyingCode(String identifyingCodeStr) {
		String message = "";
		if (TextUtils.isEmpty(identifyingCodeStr.replace(" ", ""))) {
			message = "请输入验证码！";
		} else if (identifyingCodeStr.length() < 6) {
			message = "请输入6位验证码 !";
		}
		return message;
	}

    /**获取注册验证码*/
	private void getIdentifyinCode() {
        
        new Dumpling_SinoAsyncTask<Void,Void,Dumpling_LogIn_BaseVo>(Dumpling_NoPasswordQuicklyLoginActivity.this,false,true){

            @Override
            public Dumpling_LogIn_BaseVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().NoPasswordLoginCode(phone);
            }

            @Override
            public void after(Dumpling_LogIn_BaseVo result) {
                if(result!=null){
                    if (result.getCode().equals(Dumpling_SinoConstans.LOGIN_SUCCESS_CODE)) {
                        haveTime();
                        showToast("验证码已发送");
                        verification_code_error.setVisibility(View.INVISIBLE);
                    } else if (result.getCode().equals(
                            Dumpling_SinoConstans.LOGIN_PHONE_SYSTEM_EXCEPTION)) {
                        reight_identifyingcode_btn.setClickable(true);
                        verification_code_error.setVisibility(View.VISIBLE);
                        verification_code_error
                                .setText("系统异常");
                    } else if (result.getCode().equals(Dumpling_SinoConstans.LOGIN_PHONE_BEYOND_MAX)) {
                        reight_identifyingcode_btn.setClickable(true);
                        verification_code_error.setVisibility(View.VISIBLE);
                        verification_code_error.setText("您已超过最大发送限制");
                    } else {
                        reight_identifyingcode_btn.setClickable(true);
                        verification_code_error.setVisibility(View.VISIBLE);
                        verification_code_error
                                .setText("发送验证码失败");
                    }
                }
                
            }

            @Override
            public void exception() {
                showToast("系统异常");
                reight_identifyingcode_btn.setClickable(true);
            }
        }.execute();
		
	}

	private void haveTime() {
		final Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() { // UI thread
					public void run() {
						recLen--;
						reight_identifyingcode_btn
								.setBackgroundResource(R.drawable.dumpling_nottouch_button);
						reight_identifyingcode_btn.setText(String.format("%s秒后重新发送", recLen));
						if (recLen < 1) {
							timer.cancel();
							reight_identifyingcode_btn.setClickable(true);
							recLen = 60;
							reight_identifyingcode_btn
									.setBackgroundResource(R.drawable.dumpling_apply_btn_selector_moring);
							reight_identifyingcode_btn
									.setText("重新发送");
						}
					}
				});
			}
		};
		timer.schedule(task, 1000, 1000);
	}

	private void noPWDLogin() {
        
        new Dumpling_SinoAsyncTask<Void,Void,Dumpling_LogIn_BaseVo>(Dumpling_NoPasswordQuicklyLoginActivity.this,false,true){
            @Override
            public Dumpling_LogIn_BaseVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().NoPasswordLogin(phone,
                        identifyingCodeStr, proIden);
            }

            @Override
            public void after(Dumpling_LogIn_BaseVo result) {
                if(result!=null){
                    if (result.getCode().equals(Dumpling_SinoConstans.LOGIN_SUCCESS_CODE)) {
                        if(result.getResult()!=null){
                            verification_code_error.setVisibility(View.INVISIBLE);

                            showToast("登录成功，正在为您跳转");

                            Intent intent = new Intent();
                            intent.putExtra("code", result.getCode());
                            intent.putExtra("userInfo", result.getResult());
                            intent.putExtra("index", mIndedx);
                            intent.setAction(Dumpling_SinoConstans.DUMPLING_GETMONEY_ACTION);
                            sendBroadcast(intent);
                            Intent intent1=new Intent(Dumpling_SinoConstans.DUMPLING_LOGIN_ACTION);
                            intent1.putExtra("userInfo", result.getResult());
                            sendBroadcast(intent1);
                            
                            Dumpling_NoPasswordQuicklyLoginActivity.this.finish();
                        }else{
                            showToast("登录失败，系统正在维护，请稍后重试");
                            Dumpling_NoPasswordQuicklyLoginActivity.this.finish();
                        }
                        


                    } else {
                        verification_code_error.setVisibility(View.VISIBLE);
                        verification_code_error
                                .setText("验证失败，请重新验证");
                        showToast("验证失败，请重新验证");
                    } 
                }
                
            }

            @Override
            public void exception() {
                showToast("登录失败，系统正在维护，请稍后重试!");
//                // 异常情况，code传""
//                Intent intent = new Intent();
//                intent.putExtra("code", "");
//                intent.putExtra("index", mIndedx);
//                intent.setAction(Dumpling_SinoConstans.DUMPLING_LOGIN_ACTION);
//                sendBroadcast(intent);
                Dumpling_NoPasswordQuicklyLoginActivity.this.finish();

            }
        }.execute();
        
	}

	@Override
	public void onAntiViolence(View view) {
		Intent intent = null;
		int id = view.getId();

		if (id == R.id.reight_btn) {
			// 登录
			if (phoneflag & verificationflag) {
				noPWDLogin();
			}
		} else if (id == R.id.reight_identifyingcode_btn) {
			phone = registerPhone.getText().toString();
			String validPhone = validPhone(phone);
			if (!TextUtils.isEmpty(validPhone)) { // 如果等于空就提示一下
				verification_code_error.setText(validPhone);
				verification_code_error.setVisibility(View.VISIBLE);
				return;
			}
			verification_code_error.setVisibility(View.INVISIBLE);
			// 点击之后将按钮设置为不可再点
			reight_identifyingcode_btn.setClickable(false);
			getIdentifyinCode();
		}  else if (id == R.id.quickly_login_rules) { // 服务协议
			intent = new Intent(Dumpling_NoPasswordQuicklyLoginActivity.this,
					Dumpling_KnowPassportActivity.class);
		}
		if (intent != null) {
			startActivity(intent);
		}
	}
}
